import { tagStore, todoStore } from '../lib/data-store'
import { Tag, CreateTagRequest, UpdateTagRequest } from '@data/tag'
import { v4 as uuidv4 } from 'uuid'

export class TagService {
  // 获取Tag列表
  async getTags(): Promise<Tag[]> {
    const tags = await tagStore.findAll()
    return tags.sort((a, b) => a.name.localeCompare(b.name))
  }

  // 根据ID获取Tag
  async getTagById(id: string): Promise<Tag | null> {
    const tag = await tagStore.findById(id)
    return tag || null
  }

  // 根据名称获取Tag
  async getTagByName(name: string): Promise<Tag | null> {
    const tags = await tagStore.findAll()
    const tag = tags.find((t) => t.name.toLowerCase() === name.toLowerCase())
    return tag || null
  }

  // 创建Tag
  async createTag(data: CreateTagRequest): Promise<Tag> {
    // 检查名称是否已存在
    const existing = await this.getTagByName(data.name)
    if (existing) {
      throw new Error('Tag with this name already exists')
    }

    const now = new Date().toISOString()

    const tag: Tag = {
      id: uuidv4(),
      name: data.name.trim(),
      color: data.color,
      createdAt: now,
      updatedAt: now,
    }

    return await tagStore.create(tag)
  }

  // 更新Tag
  async updateTag(id: string, data: UpdateTagRequest): Promise<Tag | null> {
    const existing = await tagStore.findById(id)
    if (!existing) {
      return null
    }

    // 如果要更新名称，检查是否与其他标签冲突
    if (data.name !== undefined) {
      const nameExists = await this.getTagByName(data.name)
      if (nameExists && nameExists.id !== id) {
        throw new Error('Tag with this name already exists')
      }
    }

    const updates: Partial<Tag> = {
      ...data,
      updatedAt: new Date().toISOString(),
    }

    if (data.name !== undefined) {
      updates.name = data.name.trim()
    }

    return await tagStore.update(id, updates)
  }

  // 删除Tag
  async deleteTag(id: string): Promise<boolean> {
    const existing = await tagStore.findById(id)
    if (!existing) {
      return false
    }

    // 从所有Todo中移除这个标签
    const todos = await todoStore.findAll()
    const todosWithTag = todos.filter((todo) => todo.tags.includes(id))

    for (const todo of todosWithTag) {
      const newTags = todo.tags.filter((tagId: string) => tagId !== id)
      await todoStore.update(todo.id, {
        tags: newTags,
        updatedAt: new Date().toISOString(),
      })
    }

    // 删除标签
    return await tagStore.delete(id)
  }

  // 获取使用指定标签的Todo数量
  async getTagUsageCount(tagId: string): Promise<number> {
    const todos = await todoStore.findAll()
    return todos.filter((todo) => !todo.deleted && todo.tags.includes(tagId)).length
  }

  // 获取所有标签的使用统计
  async getTagUsageStats(): Promise<{ tag: Tag; count: number }[]> {
    const tags = await this.getTags()
    const todos = await todoStore.findAll()
    const activeTodos = todos.filter((todo) => !todo.deleted)

    return tags
      .map((tag) => ({
        tag,
        count: activeTodos.filter((todo) => todo.tags.includes(tag.id)).length,
      }))
      .sort((a, b) => b.count - a.count)
  }

  // 批量创建标签
  async createTags(tagNames: string[], defaultColor: string = '#3b82f6'): Promise<Tag[]> {
    const createdTags: Tag[] = []

    for (const name of tagNames) {
      const trimmedName = name.trim()
      if (trimmedName) {
        // 检查是否已存在
        const existing = await this.getTagByName(trimmedName)
        if (!existing) {
          const tag = await this.createTag({
            name: trimmedName,
            color: defaultColor,
          })
          createdTags.push(tag)
        } else {
          createdTags.push(existing)
        }
      }
    }

    return createdTags
  }

  // 搜索标签
  async searchTags(query: string): Promise<Tag[]> {
    const tags = await this.getTags()
    const lowerQuery = query.toLowerCase()

    return tags.filter((tag) => tag.name.toLowerCase().includes(lowerQuery))
  }

  // 获取最常用的标签
  async getPopularTags(limit: number = 10): Promise<Tag[]> {
    const stats = await this.getTagUsageStats()
    return stats
      .filter((stat) => stat.count > 0)
      .slice(0, limit)
      .map((stat) => stat.tag)
  }

  // 合并标签 (将sourceTag的所有使用替换为targetTag)
  async mergeTags(sourceTagId: string, targetTagId: string): Promise<boolean> {
    const sourceTag = await this.getTagById(sourceTagId)
    const targetTag = await this.getTagById(targetTagId)

    if (!sourceTag || !targetTag) {
      return false
    }

    // 获取使用源标签的所有Todo
    const todos = await todoStore.findAll()
    const todosWithSourceTag = todos.filter((todo) => todo.tags.includes(sourceTagId))

    // 更新这些Todo，用目标标签替换源标签
    for (const todo of todosWithSourceTag) {
      const newTags = todo.tags
        .filter((tagId) => tagId !== sourceTagId) // 移除源标签
        .concat(targetTag.id) // 添加目标标签
        .filter((tagId, index, arr) => arr.indexOf(tagId) === index) // 去重

      await todoStore.update(todo.id, {
        tags: newTags,
        updatedAt: new Date().toISOString(),
      })
    }

    // 删除源标签
    await tagStore.delete(sourceTagId)

    return true
  }
}

export const tagService = new TagService()
